package com.framework.core.aop;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 切点类
 */
@Aspect
@Component
public class SystemValidateAspect {

    @Autowired
    private HttpServletResponse response;

    //本地异常日志记录对象
    private static final Logger logger = LoggerFactory.getLogger(SystemValidateAspect.class);


    //Controller层切点
    @Pointcut("@annotation(com.framework.core.aop.SystemControllerValidate)")
    public void controllerAspect() {
    }


    /**
     * 前置通知 用于拦截Controller层记录用户的操作
     *
     * @param joinPoint 切点
     */
    @Before("controllerAspect()")
    public void doBefore(final JoinPoint joinPoint) {
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                if (joinPoint.getArgs()[i] instanceof BindingResult) {
                    BindingResult result = (BindingResult) joinPoint.getArgs()[i];
                    Map map = new HashMap();
                    if (result.hasErrors()) {
                        map.put("result", false);
                        map.put("message", result.getFieldError().getDefaultMessage());
                        try {
                            PrintWriter pw = response.getWriter();
                            pw.write(JSON.toJSONString(map));
                            pw.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        System.out.println(result.getFieldError().getDefaultMessage());
                        return;
                        //throw new ValidateException(result.getFieldError().getDefaultMessage());
                    }
                }
            }
        }
    }


}